<?php

namespace App\Service\OpenShop\SiteLocation;


use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Enums\OpenShop\SiteLocation\SiteLocationAttachEnum;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\BaseService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\WaiMai\WaiMaiAnalysisService;
use GuzzleHttp\Exception\GuzzleException;

class SiteLocationAttachService extends BaseService
{
    //选址我的页面数据
    public static function getPersonal($authUser, $startTime, $endTime)
    {

        $param = [
            [
                'name'        => '任务时间',
                'filterType'  => 'GE',
                'filterValue' => [
                    $startTime
                ],
            ],
            [
                'name'        => '任务时间',
                'filterType'  => 'LT',
                'filterValue' => [
                    $endTime
                ],
            ],
        ];

        try {
            $tasks = GuanyuanDataService::getMonthlyCompletionOfTasks($param);
        } catch (\Exception $exception) {
            $tasks = [];
        }
        $target    = 0;
        $completed = 0;

        foreach ($tasks as $task) {
            if (mb_strpos($authUser['username'], $task['姓名']) !== false) {
                $target    += (int)$task['任务数'];
                $completed += (int)$task['推荐确址数'];
            }
        }

        $contractUpload       = 0;   //已上传
        $waitUpload           = 0;   //累计待上传
        $siteSubmitted        = 0;   //已提交
        $siteApproved         = 0;   //审核通过
        $siteRecommendAddress = 0;   //推荐址
        $siteOwnAddress       = 0;   //自带址
        $houseSubmitted       = 0;   //已提交
        $houseApprove         = 0;   //审核通过


        OpenShopSiteLocationModel::query()
            ->where('updatedAt', '>=', strtotime($startTime))
            ->where('updatedAt', '<', strtotime($endTime))
            ->where(function ($query) use ($authUser) {
                $query->where('developConsultantId', $authUser['userId'])->orWhere('developConsultantId', $authUser['userId']);
            })
            ->get()
            ->each(function (OpenShopSiteLocationModel $openShopSiteLocationModel) use (
                &$contractUpload,
                &$waitUpload,
                &$siteSubmitted,
                &$siteApproved,
                &$siteRecommendAddress,
                &$siteOwnAddress,
                &$houseSubmitted,
                &$houseApprove,
                $authUser
            ) {
                if ($openShopSiteLocationModel->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP && $openShopSiteLocationModel->developConsultantId == $authUser['userId']) {
                    if ($openShopSiteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_21) {
                        $waitUpload++;
                    }
                    if ($openShopSiteLocationModel->siteStatus > OpenShopSiteLocationModel::SITE_STATUS_1) {
                        $siteSubmitted++;
                    }
                    if ($openShopSiteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 && $openShopSiteLocationModel->ctSubmitTime) {
                        $contractUpload++;
                    }
                    if (in_array($openShopSiteLocationModel->siteStatus, [OpenShopSiteLocationModel::SITE_STATUS_4, OpenShopSiteLocationModel::SITE_STATUS_20, OpenShopSiteLocationModel::SITE_STATUS_21])) {
                        $siteApproved++;
                    }
                    if ($openShopSiteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 && in_array($openShopSiteLocationModel->messageFrom, [SiteLocationEnum::MESSAGE_FROM_TYPE_6, SiteLocationEnum::MESSAGE_FROM_TYPE_2])) {
                        $siteRecommendAddress++;
                    }
                    if ($openShopSiteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4 && in_array($openShopSiteLocationModel->messageFrom, [SiteLocationEnum::MESSAGE_FROM_TYPE_1, SiteLocationEnum::MESSAGE_FROM_TYPE_3, SiteLocationEnum::MESSAGE_FROM_TYPE_7])) {
                        $siteOwnAddress++;
                    }
                    if ($openShopSiteLocationModel->bindId > 0) {
                        $houseSubmitted++;
                        $houseApprove++;
                    }
                }

                if ($openShopSiteLocationModel->source == OpenShopSiteLocationModel::SOURCE_HOUSING && $openShopSiteLocationModel->developConsultantId == $authUser['userId']) {
                    if (in_array($openShopSiteLocationModel->clueStatus, [
                        OpenShopSiteLocationModel::CLUE_STATUS_3,
                        OpenShopSiteLocationModel::CLUE_STATUS_4,
                        OpenShopSiteLocationModel::CLUE_STATUS_5,
                        OpenShopSiteLocationModel::CLUE_STATUS_6,
                        OpenShopSiteLocationModel::CLUE_STATUS_11
                    ])) {
                        $houseSubmitted++;
                    }
                    if ($openShopSiteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_5) {
                        $houseApprove++;
                    }
                }
            });
        //获得飞书职位用户信息
        $userInfo = KmsUser::query()->where('rmsUserId', $authUser['userId'])->first();
        return [
            'cover'      => (string)optional($userInfo)->avatar,
            'name'       => $authUser['username'],
            'department' => (string)optional($userInfo)->rootDepartmentName,
            'position'   => (string)optional($userInfo)->jobTitle,
            'target'     => [
                [
                    'name'    => '目标',
                    'disable' => false,
                    'value'   => $target,
                ], [
                    'name'    => '待完成',
                    'disable' => false,
                    'value'   => $target - $completed,
                ], [
                    'name'    => '已完成',
                    'disable' => false,
                    'value'   => $completed,
                ], [
                    'name'    => '完成率',
                    'disable' => false,
                    'value'   => $target ? (round($completed / $target * 100) . '%') : '-',
                ]
            ],
            'board'      => [
                [
                    'name'  => '合同上传情况',
                    'lists' => [
                        [
                            'name'    => '已上传',
                            'disable' => true,
                            'value'   => $contractUpload,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_UPLOADED,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ], [
                            'name'    => '累计待上传',
                            'disable' => true,
                            'value'   => $waitUpload,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_PENDING_UPLOAD,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ]
                    ]
                ], [
                    'name'  => '选址情况',
                    'lists' => [
                        [
                            'name'    => '已提交',
                            'disable' => true,
                            'value'   => $siteSubmitted,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_SITE_SUBMITTED,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ], [
                            'name'    => '审核通过',
                            'disable' => true,
                            'value'   => $siteApproved,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_SITE_APPROVED,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ], [
                            'name'    => '推荐址',
                            'disable' => true,
                            'value'   => $siteRecommendAddress,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_SITE_RECOMMEND_ADDRESS,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ], [
                            'name'    => '自带址',
                            'disable' => true,
                            'value'   => $siteOwnAddress,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_SITE_OWN_ADDRESS,
                            'source'  => OpenShopSiteLocationModel::SOURCE_OPEN_SHOP
                        ]
                    ]
                ], [
                    'name'  => '房源情况',
                    'lists' => [
                        [
                            'name'    => '已提交',
                            'disable' => true,
                            'value'   => $houseSubmitted,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_HOUSE_SUBMITTED,
                            'source'  => OpenShopSiteLocationModel::SOURCE_HOUSING
                        ], [
                            'name'    => '审核通过',
                            'disable' => true,
                            'value'   => $houseApprove,
                            'key'     => SiteLocationAttachEnum::PERSONAL_KEY_HOUSE_APPROVED,
                            'source'  => OpenShopSiteLocationModel::SOURCE_HOUSING
                        ], [
                            'name'    => '通过率',
                            'disable' => false,
                            'value'   => $houseSubmitted ? (round($houseApprove / $houseSubmitted * 100) . '%') : '-',
                            'key'     => '',
                            'source'  => -1
                        ]
                    ]
                ]
            ]
        ];
    }


    /**
     * @param $authUser
     * @param $startTime
     * @param $endTime
     * @param $source
     * @param $key
     * @param $pageNum
     * @param $pageSize
     * @return array
     * @throws GuzzleException
     */

    public static function siftList($authUser, $startTime, $endTime, $source, $key, $pageNum, $pageSize): array
    {
        $paginator = OpenShopSiteLocationModel::query()
            ->where('updatedAt', '>=', strtotime($startTime))
            ->where('updatedAt', '<', strtotime($endTime))
            ->where('developConsultantId', $authUser['userId'])
            ->whereRaw(SiteLocationAttachEnum::PERSONAL_KEY_MAPPING[$key])
            ->orderByDesc('updatedAt')
            ->with([
                'signOrderRel',
                'identityCardRel',
                'baseUserInfoRel',
                'mainProcessRel',
            ])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $userList = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());
        $list     = $paginator->map(function ($item) use ($userList) {
            //判断任务类型
            if ($item->source == OpenShopSiteLocationModel::SOURCE_HOUSING && $item->bindId == OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE) {
                $info = '';
                foreach (($userList['data'] ?? []) as $user) {
                    if ($user['id'] == $item->createdByUid) {
                        $info = $user['username'];
                    }
                }
                $siteOrClue = 1;
                $cityArea   = $item->cityArea;
                $statusText = OpenShopSiteLocationModel::SITE_LOCATION_CLUE_MAPPING[$item->clueStatus];
                $status     = $item->clueStatus;
                $number     = $item->orderNo; //编号
            } else {
                $siteOrClue = 0;
                $info       = (optional($item->identityCardRel)->name ?: '-') . ' ' . (optional($item->signOrderRel)->shopCode ?: '-');
                //$cityArea   = optional($item->baseUserInfoRel)->chooseShopAddressPrefix ?: '-';  选址1.1.2优化  取消意向选址范围
                $cityArea   = $item->cityArea ?: (optional($item->baseUserInfoRel)->chooseShopAddressPrefix ?: '-');
                $statusText = OpenShopSiteLocationModel::CN_PROVINCE_STATUS[$item->siteStatus] ?? '-';
                $status     = $item->siteStatus;
                $number     = optional($item->signOrderRel)->shopCode ?: '-'; //编号
            }

            return [
                'id'                    => $item->id,
                'orderNo'               => $item->orderNo,
                'statusText'            => $statusText,
                'status'                => $status,
                'cityArea'              => $cityArea,
                'info'                  => $info,
                'updatedAt'             => date('Y-m-d H:i:s', $item->updatedAt->timestamp),
                'siteOrClue'            => $siteOrClue,
                'number'                => $number,
                'developConsultantName' => $item->developConsultantName ?: '待指派开发顾问',
                'messageFrom'           => $item->messageFrom,
                "messageFromText"       => (function ($messageFrom) {
                    $messageFromText = "";
                    switch ($messageFrom) {
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_1:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_3:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_7:
                            $messageFromText = "自带址";
                            break;
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_2:
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_6:
                            $messageFromText = "推荐址";
                            break;
                        case SiteLocationEnum::MESSAGE_FROM_TYPE_5:
                            $messageFromText = "转让";
                            break;
                    }
                    return $messageFromText;
                })($item->messageFrom),
                'tags'           => collect(OrderService::getOrderTags(
                    1,
                    SiteLocationService::tagLocationStatus($item),
                ))->where('name', '迁')->values(),
            ];
        });
        return [
            'list'      => $list,
            'count'     => $paginator->total(),
            'pageCount' => $paginator->lastPage(),
            'pageNum'   => $pageNum,
            'pageSize'  => $pageSize,
        ];

    }

    public static function nearbyTakeOut($orderNo)
    {
        $openShopSiteLocation = OpenShopSiteLocationModel::query()
            ->where('orderNo', $orderNo)
            ->first();
        if ($openShopSiteLocation == null) {
            self::throwErr('订单不存在');
        }

        // 外卖预估数据
        $takeOutData = (new WaiMaiAnalysisService())
            ->setLngLat($openShopSiteLocation->longitude, $openShopSiteLocation->latitude, 3);

        $arr = [];
        $takeOutData->getNearByShop()->each(function ($item) use (&$arr){
            $arr[] = [
                'lat' => $item['lat'],
                'lng' => $item['lng'],
                'count' => $item['orderNum'],
            ];
        });
        return $arr;
    }

    public static function preserveHeatMap($orderNo, $url)
    {
        if (is_array($url)) {
            $url = $url[0];
        }
        $fileResource = OpenShopUploadFileResourceModel::query()->firstOrCreate([
            "orderNo"   => $orderNo,
            "position"  => UploadFileResourceEnum::TAKE_OUT_HEATMAP,
        ]);
        $fileResource->url = ltrim(parse_url($url, PHP_URL_PATH), '/');
        $fileResource->isPublic = 1;
        $fileResource->save();
        return true;
    }
}
